package com.bluegalaxy.nhb.snservice.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @author:
 * @date: 2020/5/1
 * @time: 10:27
 * @description: To change this template use File | Settings | File Templates.
 */
public class FileUtil {

    private static final String tmpPath = System.getProperty("user.dir")+ File.separator + "filetmp";

    /**
     * 系统缓存环境
     */
    public static final String SYSTEM_TMP_PATH = System.getProperty("java.io.tmpdir");

    /**
     *  系统文件缓存目录
     */
    public static final String SN_FILE_TMP_PATH = SYSTEM_TMP_PATH + File.separator+ "sn_label_template" + File.separator;

    /**
     * 获取去掉文件名后缀的内容
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    /**
     * 获取临时目录
     * @return
     */
    public static String getUploadTmpDir(){
        File file = new File(System.getProperty("user.dir")+File.separator+"tmp"+File.separator+"upload");
        if (!file.exists() || !file.isDirectory()){
            file.mkdirs();
        }
        return file.getPath();
    }
    public static File getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
    /**
     * base64 转文件
     * @param base64
     * @param filePath
     * @throws IOException
     */
    public static void base642File(String base64,String filePath) throws IOException {
        byte[] out = Base64.getDecoder().decode(base64.getBytes());
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(filePath);
            if (!file.getParentFile().exists() || !file.getParentFile().isDirectory()){
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(out);
            fileOutputStream.close();
        } catch (java.io.IOException e) {
            throw e;
        }finally {
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    //下载文件
    public static void previewFiles(File file, String fileName, HttpServletResponse response) {
        try {
            byte[] buffer = null;
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1") + "");
            response.setCharacterEncoding("UTF-8");
            OutputStream outputSream = response.getOutputStream();
            if (buffer != null) {
                InputStream in = new ByteArrayInputStream(buffer);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf, 0, 1024)) != -1) {
                    outputSream.write(buf, 0, len);
                }
                outputSream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 生成pdf
     * @return
     * @throws IOException
     */
    public static File createNewPdf() throws IOException {
        File dir = getTmpPath();
        File file = new File(dir, UUID.randomUUID().toString() +".pdf");
        file.createNewFile();
        return file;
    }
    /**
     * 获取缓存路径
     * @return
     */
    public static File getTmpPath(){
        File dir = new File(SN_FILE_TMP_PATH);
        if(!dir.exists()){
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取临时文件路径
     * @param fileName 文件名称
     * @return
     */
    public static String getTmpFilePath(String fileName){
        return tmpPath + File.separator + fileName;
    }

}
